"""
Django的ORM支持通过模型创建表（正向工程），也支持通过表创建模型（反向工程）
正向工程：
python manage.py makemigrations polls
python manage.py migrate

一对一关系：OneToOneField
多对一关系：ForeignKey
多对多关系：ManyToManyField
"""
from django.db import models


# 用户的口令在数据库中不能够以原始形态保存，数据库中应该保存用户口令的摘要
# 生成摘要可以使用SHA1 / SHA256 等摘要算法，生成的摘要一般用16进制形式书写
# 对于256bit的SHA256签名来说，对应的16进制形式的字符串一共有64个字符
from polls.utils import make_sha256_digest


class User(models.Model):
    """用户"""
    userid = models.AutoField(primary_key=True, verbose_name='编号')
    username = models.CharField(max_length=20, unique=True, verbose_name='用户名')
    password = models.CharField(max_length=64, verbose_name='用户口令')
    tel = models.CharField(max_length=11, unique=True, verbose_name='手机号')
    reg_date = models.DateTimeField(auto_now_add=True, verbose_name='注册时间')
    last_visit = models.DateTimeField(null=True, verbose_name='最后登录时间')

    def save(self, *args, insert=True, **kwargs):
        if insert:
            self.password = make_sha256_digest(self.password)
        return super().save(*args, **kwargs)

    class Meta:
        db_table = 'tb_user'
        verbose_name = '用户'
        verbose_name_plural = '用户'


class Subject(models.Model):
    """学科"""
    no = models.AutoField(primary_key=True, verbose_name='编号')
    name = models.CharField(max_length=50, verbose_name='名称')
    intro = models.CharField(max_length=2000, verbose_name='介绍')
    is_hot = models.BooleanField(default=False, verbose_name='是否热门')
    create_date = models.DateField(null=True, verbose_name='成立日期')

    def __str__(self):
        return f'{self.no}: {self.name}'

    class Meta:
        db_table = 'tb_subject'
        verbose_name = '学科'
        verbose_name_plural = '学科'


class Teacher(models.Model):
    """老师"""
    no = models.AutoField(primary_key=True, verbose_name='编号')
    name = models.CharField(max_length=20, verbose_name='姓名')
    sex = models.BooleanField(default=True, choices=((True, '男'), (False, '女')), verbose_name='性别')
    birth = models.DateField(verbose_name='出生日期', help_text='出生日期的格式：yyyy/MM/dd')
    intro = models.CharField(max_length=2000, verbose_name='介绍')
    photo = models.CharField(max_length=512, verbose_name='照片')
    good_count = models.IntegerField(default=0, db_column='gcount', verbose_name='好评数')
    bad_count = models.IntegerField(default=0, db_column='bcount', verbose_name='差评数')
    subject = models.ForeignKey(to=Subject, on_delete=models.PROTECT, db_column='sno', verbose_name='所属学科')

    class Meta:
        db_table = 'tb_teacher'
        verbose_name = '老师'
        verbose_name_plural = '老师'
